package com.sharemarking.wa.platform.service.impl;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class Md5ServiceImpl {
	
	private final char[] cs=new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

	public String md5(String src) {
		MessageDigest md5=null;
		try {
			md5 = MessageDigest.getInstance("MD5");
	    } catch (NoSuchAlgorithmException ne) {
	        ne.printStackTrace();
	        return null;
	    }
		try {
			char[] resChar=new char[32];
			byte[] r=md5.digest(src.getBytes("utf-8"));
			for(int i=0;i<r.length;i++) {
				byte b=r[i];
				resChar[i*2]=cs[(b&0xff)>>4];
				resChar[i*2+1]=cs[b&0xf];
			}
			return new String(resChar);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void closeAll(Closeable... closables){
		for(Closeable closable:closables){
			try{
				if(closable!=null)closable.close();
			}catch(IOException ioe){
				ioe.printStackTrace();
			}
		}
	}

	public String md5(File file) {
		if(!file.exists())return null;
		MessageDigest md5=null;
		try {
			md5 = MessageDigest.getInstance("MD5");
	    } catch (NoSuchAlgorithmException ne) {
	        ne.printStackTrace();
	        return null;
	    }
		FileInputStream fis=null;
		String md5Str=null;
		try {
			fis=new FileInputStream(file);
			byte[] buffer=new byte[8192];
			int length=0;
			while((length=fis.read(buffer))>-1){
				md5.update(buffer,0,length);
			}
			md5Str=new String(new Hex().encode(md5.digest()));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			closeAll(fis);
		}
		return md5Str;
	}
	
}
